package valuecomusa.fijibus.eticket.shorthaul;

import android.content.*;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.*;
import valuecomusa.fijibus.eticket.Declarations;
import valuecomusa.fijibus.eticket.SunbeamActivity;
import valuecomusa.fijibus.eticket.WorkingSession;
import valuecomusa.fijibus.eticket.db.shorthaul.BusinessDBHandler;
import valuecomusa.fijibus.eticket.dto.SyncStatusValue;

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Settings extends SunbeamActivity
{
	private final String TAG = "Shorthaul-Settings";

	private ArrayAdapter<String> devicesArrayAdapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		Log.d(TAG, "[onCreate]...");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings);
		//---
		doCommon();
		//---
        Button btn2 = (Button)findViewById(R.id.settings_btn_test_print);
		btn2.setOnClickListener(PrintTestHandler);
		//--
        SharedPreferences sp = getSharedPreferences(Declarations.ShortHaul_SharedPrefName, MODE_PRIVATE);
        String cachePrinterAddress = sp.getString("PrinterAddress", "");
        if(cachePrinterAddress.length() > 0)
        {
            EditText printAddress = (EditText) findViewById(R.id.setting_printer_address);
            printAddress.setText(cachePrinterAddress);
            WorkingSession.getInstance().wifiPrinterAddress = cachePrinterAddress;
        }
		//--
		CheckBox printReceipt = (CheckBox)findViewById(R.id.settings_checkbox_print_receipt);
		printReceipt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
		{
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
			{
				BusinessDBHandler db = new BusinessDBHandler(Settings.this);
				db.addOrUpdateRuntimeValues("print-receipt", isChecked? "1": "0");
				//--
				if(isChecked)
					WorkingSession.getInstance().printReceipt = true;
				else
					WorkingSession.getInstance().printReceipt = false;
			}
		});
        //--
        String bmfSam = sp.getString("BMF-Sam-Slot", "");
        if(bmfSam.length() > 0)
        {
            EditText samSlot = (EditText) findViewById(R.id.setting_bmf_sam_slot);
            samSlot.setText(bmfSam);
            WorkingSession.getInstance().setSAMBmfSlot(Integer.parseInt(bmfSam));
        }
        String vodaSam = sp.getString("Voda-Sam-Slot", "");
        if(vodaSam.length() > 0)
        {
            EditText samSlot = (EditText) findViewById(R.id.setting_voda_sam_slot);
            samSlot.setText(vodaSam);
            WorkingSession.getInstance().setSAMVodaSlot(Integer.parseInt(vodaSam));
        }
        String digicelSam = sp.getString("Digicel-Sam-Slot", "");
        if(digicelSam.length() > 0)
        {
            EditText samSlot = (EditText) findViewById(R.id.setting_digicel_sam_slot);
            samSlot.setText(digicelSam);
            WorkingSession.getInstance().setSAMDigiCelSlot(Integer.parseInt(digicelSam));
        }
	}

    @Override
    protected void onStart()
    {
        super.onStart();
        Log.i(TAG, "onStart...");
        //--
        try
        {
            getWindow().setSoftInputMode(
                    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        //------------------------------------
        //Data Synchronous status
        //------------------------------------
        BusinessDBHandler db = new BusinessDBHandler(Settings.this);
        SyncStatusValue syncInfo = db.getLastSync();

        TextView textStatus = (TextView)findViewById(R.id.setting_sync_status);
        TextView textNext = (TextView) findViewById(R.id.setting_next_sync);
        TextView textLastUpdate = (TextView) findViewById(R.id.setting_last_sync);

        if(syncInfo == null)
        {
            textStatus.setText("");
            textNext.setText("");
            textLastUpdate.setText("");

            return;
        }

        //--
        textStatus.setText(syncInfo.Status);
        if(syncInfo.Status.length() > 0 && !syncInfo.Status.equals("Successful"))
            textStatus.setTextColor(Color.rgb(255,0,0));
        //---
        textNext.setText(syncInfo.NextSync);
        //---
        textLastUpdate.setText(syncInfo.LastUpdate);
		//--
		CheckBox printReceipt = (CheckBox)findViewById(R.id.settings_checkbox_print_receipt);
		String x = db.getRuntimeValues("print-receipt");
		if(x == null || x.length() == 0)
			x = "1";
		printReceipt.setChecked(x.equals("1"));
		//--
		EditText transToRestart = (EditText)findViewById(R.id.setting_transaction_restart);
		transToRestart.setText(String.valueOf(WorkingSession.getInstance().transactionsToRestart));
    }

	@Override
	protected void onPause()
	{
		EditText transToRestart = (EditText)findViewById(R.id.setting_transaction_restart);
		if(transToRestart != null)
		{
			int x = 200;
			try
			{
				x = Integer.parseInt(transToRestart.getText().toString());
			}
			catch (Exception ex)
			{
				Log.e(TAG, "[onPause] Parse Transactions to restart failed. " + ex.toString());
			}
			BusinessDBHandler db = new BusinessDBHandler(Settings.this);
			db.addOrUpdateRuntimeValues("transactions-to-restart", String.valueOf(x));
			WorkingSession.getInstance().transactionsToRestart = x;
		}
        //---Sep29.2014
        SharedPreferences sp = getSharedPreferences(Declarations.ShortHaul_SharedPrefName, MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        EditText samSlot = (EditText) findViewById(R.id.setting_bmf_sam_slot);
        WorkingSession.getInstance().setSAMBmfSlot(Integer.parseInt(samSlot.getText().toString()));
        //WorkingSession.getInstance().SAM_BmfSlot = samSlot.getText().toString();
        editor.putString("BMF-Sam-Slot", samSlot.getText().toString());
        //--
        samSlot = (EditText) findViewById(R.id.setting_voda_sam_slot);
        WorkingSession.getInstance().setSAMVodaSlot(Integer.parseInt(samSlot.getText().toString()));
        //WorkingSession.getInstance().SAM_VodaSlot = samSlot.getText().toString();
        editor.putString("Voda-Sam-Slot", samSlot.getText().toString());
        //--
        samSlot = (EditText) findViewById(R.id.setting_digicel_sam_slot);
        WorkingSession.getInstance().setSAMDigiCelSlot(Integer.parseInt(samSlot.getText().toString()));
        //WorkingSession.getInstance().SAM_DigicelSlot = samSlot.getText().toString();
        editor.putString("Digicel-Sam-Slot", samSlot.getText().toString());
        editor.commit();
        //--

		super.onPause();
	}

	@Override
	protected void onDestroy()
	{
		Log.d(TAG, "[onDestroy]...");
		super.onDestroy();
	}
	
	View.OnClickListener PrintTestHandler = new View.OnClickListener()
	{		
		@Override
		public void onClick(View v)
		{
            WorkingSession.getInstance().HideKeyboard(Settings.this);
            //--
            TextView errMsg = (TextView) findViewById(R.id.setting_error_text);
            errMsg.setText("");
            //--
            EditText printAddress = (EditText) findViewById(R.id.setting_printer_address);
            //--
            String ipAddress = printAddress.getText().toString();
            if(ipAddress.length() == 0)
            {
                errMsg.setText("Please enter Printer IP Address");
                return;
            }
            if(!ipAddress.matches("^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$"))
            {
                errMsg.setText("Invalid IP Address");
                return;
            }

            WorkingSession.getInstance().wifiPrinterAddress = ipAddress;
            SharedPreferences sp = getSharedPreferences(Declarations.ShortHaul_SharedPrefName, MODE_PRIVATE);
            sp.edit().putString("PrinterAddress", ipAddress).commit();

            String msg = "\n--------------------------------\n" +
                    getString(R.string.app_name) + "\n" +
                    getString(R.string.version) + "\n\n"
                    + (new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aaa")).format(Calendar.getInstance().getTime())
                    + "\n--------------------------------\n\n";
            int rs = WorkingSession.getInstance().PreparePrintReceiptWifi(Settings.this, msg, wifiPrintStateHandler);

            if(rs == Declarations.PRINT_RECEIPT_ERROR)
                errMsg.setText("Print test page failed.");
            else
            {
                Button btn = (Button)findViewById(R.id.settings_btn_test_print);
                btn.setEnabled(false);
            }
		}
	};

	private final Handler wifiPrintStateHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			Button btn = (Button)findViewById(R.id.settings_btn_test_print);
            btn.setEnabled(true);
            //--
            TextView errMsg = (TextView) findViewById(R.id.setting_error_text);
            errMsg.setText("");
			switch (msg.what)
			{
				case Declarations.WIFI_PRINTER_CONNECTED:
					WorkingSession.getInstance().ShowToast(Settings.this,
							"Printer connected", Toast.LENGTH_SHORT);
					WorkingSession.getInstance().PrintReceipt();
					break;
				case Declarations.WIFI_PRINTER_CONNECTED_ERR:
                    errMsg.setText("Unable connect to printer");
					break;
                case Declarations.WIFI_PRINTER_SEND_FAILED:
                    errMsg.setText("Unable send data to printer");
                    break;
                case Declarations.PRINT_RECEIPT_SUCCESSFUL:
                    WorkingSession.getInstance().ShowToast(Settings.this,
                            "Print successful", Toast.LENGTH_SHORT);
                    break;
			}
		}

	};
}
